import sys

from PySide6.QtWidgets import QApplication, QMainWindow, QTableView
from PySide6.QtCore import QSize, Qt
from PySide6.QtSql import QSqlDatabase, QSqlTableModel

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        db = QSqlDatabase.addDatabase('QSQLITE')
        db.setDatabaseName("Chinook_Sqlite.sqlite")
        if not db.open():
            print("无法打开数据库")
            return
        
        self.table = QTableView()
        self.model = QSqlTableModel(db=db)
        self.model.setEditStrategy(QSqlTableModel.OnManualSubmit)

        self.table.setModel(self.model)
        self.model.setTable("Track")

        column_titles = {
            "Name": "Name",
            "AlbumId": "Album (ID)",
            "MediaTypeId": "Media Type (ID)",
            "GenreId": "Genre (ID)",
            "Composer": "Composer"
        }

        self.model.setSort(2, Qt.AscendingOrder)
        # self.model.setHeaderData(1, Qt.Horizontal, "Name")
        # self.model.setHeaderData(2, Qt.Horizontal, "Album (ID)")
        # self.model.setHeaderData(3, Qt.Horizontal, "Media Type (ID)")
        # self.model.setHeaderData(4, Qt.Horizontal, "Genre (ID)")
        # self.model.setHeaderData(5, Qt.Horizontal, "Composer")
        # 添加列的标题
        # for n, t in column_titles.items():
        #     idx = self.model.fieldIndex(n)
        #     self.model.setHeaderData(idx, Qt.Horizontal, t)

        # 删除 2 到 5 列
        # self.model.removeColumns(2, 5)
        
        # 删除指定列，根据 fieldIndex 查询
        # column_to_remove = ['name', 'something']
        # for cn in column_to_remove:
        #     idx = self.model.fieldIndex(cn)
        #     self.model.removeColumns(idx, 1)

        ret = self.model.select()
        print("select: ", ret)

        self.setMinimumSize(QSize(1204, 600))
        self.setCentralWidget(self.table)

app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()